import { Button, Space, Tree } from 'antd'
import React, { useState, useEffect } from 'react'
import AppDialog from '../../components/AppDialog'
import Message from '../../components/Message';
import { setRoleRights } from "../../api/roles.js"

const SetRights = ({ visible, roleInfo, onHide, rightsTree }) => {

  const [checkedKeys, setCheckedKeys] = useState([])
  const [halfCheckedKeys, setHalfCheckedKeys] = useState([])
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (visible && roleInfo.id) {
      let selectKey = []
      getLeafKeys(roleInfo, selectKey)
      setCheckedKeys(selectKey)
    }
  }, [roleInfo])

  // 通过递归形式获取角色下所有三级权限的ID，并保存到defKeys数组中
  const getLeafKeys = (node, arr) => {
    // 如果当前node节点不包含children属性则是三级节点
    if (!node.children) {
      return arr.push(node.id);
    }
    node.children.forEach((item) => {
      getLeafKeys(item, arr);
    });
  };

  // 选择 
  const onCheck = (checkedKeys, info) => {
    setCheckedKeys(checkedKeys)
    setHalfCheckedKeys(info.halfCheckedKeys)
  };

  // 点击确定
  const onFinish = async () => {
    setLoading(true)
    const keys = [...checkedKeys, ...halfCheckedKeys]
    const idStr = keys.join(",");
    await setRoleRights(roleInfo.id, idStr).finally(() => {
      setLoading(false)
    });
    Message("success", "分配权限成功");

    handleDialogClosed('success')
  };

  // 点击取消
  const handleDialogClosed = (type) => {
    onHide(type)
  };

  return (visible ?
    <AppDialog
      title="分配权限"
      visible={visible}
      onClosed={handleDialogClosed}
    >
      <Tree
        checkable
        defaultExpandAll
        fieldNames={{ title: "authName", key: "id", children: "children" }}
        checkedKeys={checkedKeys}
        treeData={rightsTree}
        onCheck={onCheck}
      />
      <Space className='set-rights-but'>
        <Button type="primary" onClick={onFinish} loading={loading}>确定</Button>
        <Button onClick={() => handleDialogClosed()}>取消</Button>
      </Space>
    </AppDialog>
    : null
  )
}

export default SetRights
